<template>
    <a-modal :keyboard="false" :maskClosable="false" title="分类编辑" :open="visible" :width="700" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="分类名称" v-bind="validateInfos.classifyName">
                        <a-input v-model:value="modelRef.classifyName" />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="归属条线" v-bind="validateInfos.orderProfessionalLine">
                        <a-select v-model:value="modelRef.orderProfessionalLine" style="width: 100%" allow-search>
                            <a-select-option v-for="item in roleList" :key="item.id" :value="item.name">{{ item.name }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="父级分类" v-bind="validateInfos.orderType">
                        <a-radio-group v-model:value="modelRef.orderType">
                            <a-radio v-for="(key, value) in typeMap" :value="Number(value)" :key="value">{{ key }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24" v-if="modelRef.orderType === 0">
                    <a-form-item label="对应类型" v-bind="validateInfos.orderTypeSub">
                        <a-checkbox-group v-model:value="modelRef.orderTypeSub">
                            <a-checkbox v-for="(item, index) in options" :key="index" :value="item.value" :label="item.label">{{ item.label }}</a-checkbox>
                        </a-checkbox-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="分类状态" v-bind="validateInfos.status">
                        <a-radio-group v-model:value="modelRef.status">
                            <a-radio :value="1">启用</a-radio>
                            <a-radio :value="0">禁用</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { createOrderClassify, updateOrderClassify } from '@/api/order/cate';
    import { cloneDeep, isEmpty, isUndefined } from 'lodash-es';
    import type { TreeProps } from 'ant-design-vue';
    import { txList } from '@/api/common/proline';

    const fieldNames: TreeProps['fieldNames'] = {
        children: 'children',
        title: 'name',
        key: 'code',
    };

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const options = [
                {
                    label: '户内',
                    value: '0',
                },
                {
                    label: '公区',
                    value: '1',
                },
            ];

            const typeMap = {
                '0': `报事报修`,
                '1': `投诉`,
            };
            const roleList = ref<any[]>([]);
            const defaultForm = {
                status: 1,
                classifyName: '',
                orderProfessionalLine: '',
                orderType: '',
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));

            const rulesRef = reactive({
                classifyName: [{ required: true, message: '请输入分类名称' }],
                orderProfessionalLine: [{ required: true, message: '请选择条线' }],
                orderType: [{ required: true, message: '请选择父级分类' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    txList().then(res => {
                        if (!isEmpty(res.data)) roleList.value = res.data;
                    });

                    if (props.model) {
                        Object.assign(modelRef, props.model, {
                            orderTypeSub: isEmpty(props.model.orderTypeSub) ? [] : props.model.orderTypeSub.split(','),
                        });
                        // Object.assign(modelRef, props.model);
                        // 这一步可以不用，直接传递 model.permissions 到页面进行渲染
                        // 这里重新组装是为了演示结构不相同情况下可以按照下列方案组装结构
                    }
                }
            });

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;

                    (isUndefined(modelRef.id) ? createOrderClassify : updateOrderClassify)({
                        ...(modelRef as any),
                        orderTypeSub: modelRef.orderTypeSub.join(','),
                    })
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                fieldNames,
                typeMap,
                options,
                roleList,

                isEmpty,
            };
        },
        components: {},
    });
</script>
